/******************************************************************************\
    Memory.hpp contains a class of self-destructing memory object.
    Copyright (C) 2008  Victor Vinogradov (fly3333@gmail.com)

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
\******************************************************************************/

#ifndef __MEMORY_HPP
#define __MEMORY_HPP

#include ".\Object.hpp"

template< class cType >
class cSubMemory : public cSubObject
{
	cType *Data;
public:
	cSubMemory( cType *data )
		: Data( data )
	{
	}
	virtual ~cSubMemory()
	{
		delete[] Data;
	}
	cType *Pointer() const 
	{
		return Data;
	}
};

template< class cType >
class cMemory : public cObject< cSubMemory< cType > >
{
public:
	cMemory()
	{
	}
	cMemory( size_t size )
	{
		cSubMemory< cType > *sub_object = NULL;
		try
		{
			cType *memory = new cType[ size ];
			try
			{
				sub_object = new cSubMemory< cType >( memory );
			}
			catch( ... )
			{
				delete[] memory;
			}
		}
		catch( ... )
		{
		}
		SwitchToSubObject( sub_object );
	}
	operator cType *() const
	{
		if( GetSubObject() == NULL )
			return NULL;
		return GetSubObject()->Pointer();
	}
};

#endif
